package com.creaylei.stock.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.util.Assert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author zhang lei
 * @Date 2022-03-13 20:37
 */
public class TimeUtil extends DateUtils {

    public static final String DATE_PATTERN = "yyyy-MM-dd";

    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_TIME_PATTERN2 = "yyyy/MM/dd HH:mm:ss";

    public static final String ZERO_DATE = "1970-01-01 08:00:00";

    public static String dateToDateString(Date date) {
        if(null == date) {
            return null;
        }
        return dateToString(date, DATE_PATTERN);
    }

    public static String dateToString(Date date, String pattern) {
        Assert.notNull(date, "指定日期为null");
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public static Date dateTimeStrToDate(String dateTimeStr) {
        if(StringUtils.isEmpty(dateTimeStr)) {
            return null;
        }
        return timeStrToDate(dateTimeStr, DATE_TIME_PATTERN);
    }

    /**
     * String转为Date
     * @param timeStr
     * @param pattern
     * @return
     */
    public static Date timeStrToDate(String timeStr, String pattern) {
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        try {
            date =  sdf.parse(timeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
